package com.xuedongzhilian.controller;

import com.xuedongzhilian.dto.Result;
import com.xuedongzhilian.dto.CircleDTO;
import com.xuedongzhilian.entity.Circle;
import com.xuedongzhilian.entity.CircleMember;
import com.xuedongzhilian.service.ICircleService;
import com.xuedongzhilian.service.ICircleMemberService;
import com.xuedongzhilian.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 圈子控制器
 * </p>
 *
 * @author 学动智联团队
 * @since 2025-10-14
 */
@Slf4j
@RestController
@RequestMapping("/circle")
public class CircleController {

    @Resource
    private ICircleService circleService;
    
    @Resource
    private ICircleMemberService circleMemberService;

    /**
     * 创建圈子
     */
    @PostMapping
    public Result createCircle(@RequestBody CircleDTO circleDTO) {
        Long userId = UserHolder.getUser().getId();
        
        log.info("用户 {} 开始创建圈子，圈子名称: {}", userId, circleDTO.getName());
        
        Circle circle = new Circle();
        BeanUtils.copyProperties(circleDTO, circle);
        circle.setCreatorId(userId);
        circle.setMemberCount(1); // 创建者自动成为成员
        circle.setPostCount(0);
        circle.setStatus(1); // 正常状态
        circle.setCreateTime(LocalDateTime.now());
        circle.setUpdateTime(LocalDateTime.now());
        
        boolean success = circleService.save(circle);
        if (success) {
            log.info("圈子创建成功，圈子ID: {}, 名称: {}", circle.getId(), circle.getName());
            
            // 创建者自动成为圈主
            CircleMember member = new CircleMember();
            member.setCircleId(circle.getId());
            member.setUserId(userId);
            member.setRole(3); // 圈主
            member.setJoinTime(LocalDateTime.now());
            member.setCreateTime(LocalDateTime.now());
            member.setUpdateTime(LocalDateTime.now());
            
            boolean memberSuccess = circleMemberService.save(member);
            if (memberSuccess) {
                log.info("圈主成员关系创建成功，用户ID: {}, 圈子ID: {}", userId, circle.getId());
            } else {
                log.error("圈主成员关系创建失败，用户ID: {}, 圈子ID: {}", userId, circle.getId());
            }
            
            return Result.ok(circle);
        } else {
            log.error("圈子创建失败，用户ID: {}, 圈子名称: {}", userId, circleDTO.getName());
            return Result.fail("创建失败");
        }
    }

    /**
     * 获取圈子列表
     */
    @GetMapping
    public Result getCircles(@RequestParam(required = false) String keyword,
                            @RequestParam(defaultValue = "1") Integer current,
                            @RequestParam(defaultValue = "10") Integer size) {
        List<Circle> circles = circleService.lambdaQuery()
                .like(keyword != null && !keyword.isEmpty(), Circle::getName, keyword)
                .or()
                .like(keyword != null && !keyword.isEmpty(), Circle::getDescription, keyword)
                .eq(Circle::getStatus, 1) // 只获取正常状态的圈子
                .orderByDesc(Circle::getMemberCount)
                .page(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size))
                .getRecords();
                
        return Result.ok(circles);
    }

    /**
     * 获取圈子详情
     */
    @GetMapping("/{id}")
    public Result getCircleDetail(@PathVariable Long id) {
        Circle circle = circleService.getById(id);
        if (circle == null || circle.getStatus() != 1) {
            return Result.fail("圈子不存在或已被解散");
        }
        return Result.ok(circle);
    }

    /**
     * 加入圈子
     */
    @PostMapping("/join/{id}")
    public Result joinCircle(@PathVariable Long id) {
        Long userId = UserHolder.getUser().getId();
        Circle circle = circleService.getById(id);
        
        if (circle == null || circle.getStatus() != 1) {
            return Result.fail("圈子不存在或已被解散");
        }
        
        // 检查是否已加入
        CircleMember existingMember = circleMemberService.lambdaQuery()
                .eq(CircleMember::getCircleId, id)
                .eq(CircleMember::getUserId, userId)
                .one();
                
        if (existingMember != null) {
            return Result.fail("您已加入该圈子");
        }
        
        // 创建成员记录
        CircleMember member = new CircleMember();
        member.setCircleId(id);
        member.setUserId(userId);
        member.setRole(1); // 普通成员
        member.setJoinTime(LocalDateTime.now());
        member.setCreateTime(LocalDateTime.now());
        member.setUpdateTime(LocalDateTime.now());
        
        boolean success = circleMemberService.save(member);
        if (success) {
            // 更新圈子成员数
            circle.setMemberCount(circle.getMemberCount() + 1);
            circle.setUpdateTime(LocalDateTime.now());
            circleService.updateById(circle);
            
            return Result.ok("加入成功");
        } else {
            return Result.fail("加入失败");
        }
    }

    /**
     * 退出圈子
     */
    @PostMapping("/leave/{id}")
    public Result leaveCircle(@PathVariable Long id) {
        Long userId = UserHolder.getUser().getId();
        Circle circle = circleService.getById(id);
        
        if (circle == null || circle.getStatus() != 1) {
            return Result.fail("圈子不存在或已被解散");
        }
        
        // 检查是否是圈主
        CircleMember member = circleMemberService.lambdaQuery()
                .eq(CircleMember::getCircleId, id)
                .eq(CircleMember::getUserId, userId)
                .one();
                
        if (member == null) {
            return Result.fail("您未加入该圈子");
        }
        
        if (member.getRole() == 3) {
            return Result.fail("圈主不能退出圈子");
        }
        
        // 删除成员记录
        boolean success = circleMemberService.removeById(member.getId());
        if (success) {
            // 更新圈子成员数
            circle.setMemberCount(Math.max(0, circle.getMemberCount() - 1));
            circle.setUpdateTime(LocalDateTime.now());
            circleService.updateById(circle);
            
            return Result.ok("退出成功");
        } else {
            return Result.fail("退出失败");
        }
    }

    /**
     * 获取我的圈子
     */
    @GetMapping("/my")
    public Result getMyCircles() {
        Long userId = UserHolder.getUser().getId();
        
        // 查询用户加入的所有圈子
        List<Long> circleIds = circleMemberService.lambdaQuery()
                .eq(CircleMember::getUserId, userId)
                .list()
                .stream()
                .map(CircleMember::getCircleId)
                .collect(java.util.stream.Collectors.toList());
                
        if (circleIds.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        
        List<Circle> circles = circleService.lambdaQuery()
                .in(Circle::getId, circleIds)
                .eq(Circle::getStatus, 1)
                .list();
                
        return Result.ok(circles);
    }
}